import { defineComponent, ref, watch } from 'vue';

export function useModel<T>(getter: () => T, emitter: (value: T) => void) {
  const state = ref(getter()) as { value: T };

  watch(getter, (value) => {
    if (value !== state.value) {
      state.value = value
    }
  })

  return {
    get value() {
      return state.value;
    },
    set value(value) {
      if (state.value !== value) {
        state.value = value;
        emitter(value);
      }
    }
  }
}

export const TestUseModel = defineComponent({
  props: {
    modelValue: {
      type: String,
    }
  },
  emits: {
    'update.modelValue': (val?: string) => true,
  },
  setup(props, context) {
    console.log(props, context);
    const model = useModel(() => props.modelValue, (value) => {
      context.emit('update.modelValue', value);
    });

    return () => (
      <div>
        test userModel
        <input type="text" v-model={model.value} />
        <p>{model.value}</p>
      </div>
    )
  }
});
